//
//  LoginPageViewController.m
//
//
//  Created by ypj on 2021/11/29.
//

#import "LoginPageViewController.h"
#import "RegistViewController.h"
#import "ForgetViewController.h"
#import "PersonInfoViewController.h"
#import "CreateQiYeViewController.h"
#import "SuoShuQiYeViewController.h"
#import "XIeYiPageVC.h"
#import "NSData+YYAdd.h"
#import "AESCipher.h"
#import "JSONMgr.h"
#import "CitiesListView.h"

@interface LoginPageViewController ()

@property(nonatomic,  strong) NSString * typeString;
@property (nonatomic, assign) NSInteger  timeout;
@property (nonatomic, strong) NSTimer  * timer;
@property(nonatomic,  strong) NSString * agreeString;

@end

@implementation LoginPageViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[MSStorageUtils shareInstance] userDefaultSave:@"NO" withKey:USER_DEFAULT_KEY_MEMBER_IsLogin];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self addNotify];
   
    [self layoutCustomNav:self.view title:@"登录"];
    
    YLUserInfo *info = [YLUserMgr fetchUser];
    //info.enterpriseName.length == 0 || info.realName.length == 0 ||
    
    if (info.realName.length > 0)
        //        [NSString stringWithFormat:@"%@",info.companyId].length < 1 ||
//        [NSString isempty:[NSString stringWithFormat:@"%@",info.companyId]] ||
//        ([info.companyId intValue] < 1 || [[[MSStorageUtils shareInstance] userDefaultGet:USER_DEFAULT_KEY_MEMBER_IsLogin] isEqualToString:@"YES"]) ||
//        [info.companyId isNil] == YES)
    {
        SuoShuQiYeViewController *suoshuVC = [[SuoShuQiYeViewController alloc] init];
        suoshuVC.isFromeLogin = YES;
        [self.navigationController pushViewController:suoshuVC animated:YES];
    }
    
    self.phoneTF.delegate = self;
    self.codeTF.delegate = self;
    self.agreeString = @"0";
    self.typeString = @"0";
    self.codeTF.text = @"";
    [self.loginImage createBordersWithColor:nil withCornerRadius:5.0 andWidth:0];
    self.changeButton.selected = YES;
   [self.changeButton setImage:Image(@"small_unSelect_icon") forState:UIControlStateNormal];

    self.phoneClearButton.hidden=YES;
    self.passLine.hidden = YES;
    self.duanXinLine.hidden = NO;
    self.codeButton.hidden = NO;
    self.codeTF.placeholder = @"请输入验证码";
    self.codeTF.keyboardType = UIKeyboardTypeNumberPad;
    [self.passTypeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.DuanXinTypeButton setTitleColor:mainColor forState:UIControlStateNormal];
    [self.loginButton createBordersWithColor:nil withCornerRadius:4.0 andWidth:0];
    [self.codeClearButton whenTapped:^{
        self.codeTF.text = @"";
    }];
    [self.phoneClearButton whenTapped:^{
        self.phoneTF.text = @"";
    }];
    //切换验证码登录
    [self.DuanXinTypeButton whenTapped:^{
        [self.phoneTF resignFirstResponder];
        [self.codeTF resignFirstResponder];
        self.typeString = @"0";
        self.codeTF.keyboardType = UIKeyboardTypeNumberPad;
        self.phoneTF.keyboardType = UIKeyboardTypeNumberPad;
        self.phoneClearButton.hidden = YES;
        [self.passTypeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        self.passLine.hidden = YES;
        self.duanXinLine.hidden = NO;
        [self.DuanXinTypeButton setTitleColor:mainColor forState:UIControlStateNormal];
        self.codeButton.hidden = NO;
        self.codeTF.text = @"";
        self.codeTF.placeholder = @"请输入验证码";
        self.phoneTF.placeholder = @"请输入手机号";
    }];
    //切换密码登录
    [self.passTypeButton whenTapped:^{
        [self.phoneTF resignFirstResponder];
        [self.codeTF resignFirstResponder];
        self.typeString = @"1";
        self.codeTF.keyboardType = UIKeyboardTypeASCIICapable;
        self.phoneTF.keyboardType = UIKeyboardTypeURL;
        self.phoneClearButton.hidden = NO;
        [self.passTypeButton setTitleColor:mainColor forState:UIControlStateNormal];
        self.passLine.hidden = NO;
        self.duanXinLine.hidden = YES;
        [self.DuanXinTypeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        self.codeButton.hidden = YES;
        self.codeTF.text = @"";
        self.codeTF.placeholder = @"请输入登录密码";
        self.phoneTF.placeholder = @"请输入账号";
    }];
    //获取验证码
    [self.codeButton whenTapped:^{
        [self.view endEditing:YES];
        [self getCodeData];
    }];
    
    //登录
    [self.loginButton whenTapped:^{
        if ([self.typeString isEqualToString:@"1"]){
            [self  passWordLogin];
        } else {
            [self  codeLogin];
        }
    }];
    
    //注册
    [self.registButton whenTapped:^{
        RegistViewController  *VC = [[RegistViewController alloc] init];
        [self.navigationController pushViewController:VC animated:YES];
    }];
    
    //平台协议
    [self.xieYiButton whenTapped:^{
        XIeYiPageVC *VC = [[XIeYiPageVC alloc] init];
        VC.titleString = @"平台服务协议";
        VC.type = @"1";
        [self.navigationController pushViewController:VC animated:YES];
    }];
    //隐私协议
    [self.yinSiButton whenTapped:^{
        XIeYiPageVC  *VC = [[XIeYiPageVC alloc] init];
        VC.titleString = @"隐私协议";
        VC.type = @"2";
        [self.navigationController pushViewController:VC animated:YES];
    }];
    //忘记密码
    [self.forgetButton whenTapped:^{
        ForgetViewController *VC = [[ForgetViewController alloc] init];
        [self.navigationController pushViewController:VC animated:YES];
    }];
    [self.view whenTapped:^{
        [self.view endEditing:YES];
    }];

}

#pragma mark----网络判定、获取验证码、倒计时处理、密码登录、验证码登录、协议勾选
- (void)addNotify {
    [[kNotifyCenter rac_addObserverForName:UIApplicationDidBecomeActiveNotification object:nil] subscribeNext:^(NSNotification * _Nullable note) {
        [AppDelegate monitorNetworking];
    }];
    [[kNotifyCenter rac_addObserverForName:YLNetworkNotify object:nil] subscribeNext:^(NSNotification * _Nullable note) {
        if ([AFNetworkReachabilityManager sharedManager].isReachable) { //有网络
        } else { //无网络
            UIViewController *rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
            if ([rootVC isKindOfClass:[UINavigationController class]]) {
                UINavigationController *navVC = (UINavigationController *)rootVC;
                if ([navVC.topViewController isKindOfClass:[self class]]) {
                    [MSNetworkManager showNoNetAlert];
                }
            }
        }
    }];
}

///获取验证码
-(void)getCodeData{
//    [self chooseAddress];
    if (![_phoneTF.text isValidPhone]){
        showAlert(@"手机号码不正确");
        return;
    }
    
    self.codeButton.enabled = NO;
    
    NSString *url = [NSString stringWithFormat:@"%@?phone=%@",BEFORE_SMS_URL,self.phoneTF.text];
    
    [MSNetworkManager postRevertUrl:url params:@{} success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        if (isSuccess) {
            showAlert(@"获取验证码成功");
            self.timeout = kCodeTime;
            [self.codeButton setTitle:[NSString stringWithFormat:@"%d秒", kCodeTime] forState:UIControlStateNormal];
            [self applicationEnterBackground];
            [[kNotifyCenter rac_addObserverForName:UIApplicationDidEnterBackgroundNotification object:nil] subscribeNext:^(NSNotification * _Nullable note){
                [self applicationEnterBackground];
            }];
        } else {
            [self msgCodeFail];
        }
        
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
        [self msgCodeFail];
        showAlert(@"验证码获取失败");
    } withShowHud:YES];
    

}


- (void)applicationEnterBackground {
    [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
    //加入定时器，用来控制后台运行时间
    if (!_timer) {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDown) userInfo:nil repeats:YES];
        //[_timer fire];
    }
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}

- (void)countDown {
    _timeout--;
    [self.codeButton setTitle:[NSString stringWithFormat:@"%ld秒",(long)_timeout] forState:UIControlStateNormal];
    if (_timeout == 0){
        [self msgCodeFail];
    }
}
- (void)msgCodeFail {
    [_timer invalidate];
    _timer = nil;
    [_codeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    _codeButton.enabled = YES;
    _timeout = kCodeTime;
}

///密码登录
-(void)passWordLogin{
    [self.view endEditing:YES];
//    if (![self.phoneTF.text isValidPhone]) {
//        showAlert(@"手机号码不正确");
//        return;
//    }
    if (self.codeTF.text.length == 0||self.codeTF.text.length<8){
        showAlert(@"账号或密码错误");
        return;
    }
    if (self.codeTF.text.length>18){
        showAlert(@"账号或密码错误");
        return;
    }
//    if ([self.codeTF.text isValidPwd]==NO) {
//        showAlert(@"密码必须为数字英文混合设置");
//        return;
//    }
    if ([self.agreeString isEqualToString:@"0"]){
        showAlert(@"请先阅读平台服务协议和隐私协议");
        return;
    }
    //aes加密
//    NSString *cipherText = aesEncryptString(self.codeTF.text, @"thanks,pig4cloud");
    NSString *cipherText = self.codeTF.text;
WEAKSELF
    NSString *url = [NSString stringWithFormat:@"%@%@?password=%@&username=%@&grant_type=password",DOMAIN_URL,LOGIN_URL, cipherText, self.phoneTF.text];
   
    
    [self loadLogin:url];
    
   
}


- (void)getUserInfo {
    
    
    NSString *url = [NSString stringWithFormat:@"%@%@",DOMAIN_URL,USER_URL];

    [MSNetworkManager getRevertUrl:url params:@{} success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        
        if(isSuccess){
            NSDictionary *objects = resonseObj[@"sysUser"];
            //        YLUserInfo * info = [YLUserMgr fetchUser];
            [self saveUserInfo:objects];
            YLUserInfo *infoNew = [YLUserMgr fetchUser];
            // 用户ID
            [[MSStorageUtils shareInstance] userDefaultSave:objects[@"userId"] withKey:U_Id];
            // 用户聊天
            [[MSStorageUtils shareInstance] userDefaultSave:objects[@"imAccount"] withKey:U_Im_Token];
            // 用户真实姓名
            [[MSStorageUtils shareInstance] userDefaultSave:objects[@"realNmae"] withKey:U_Name];
            // 用户头像
            [[MSStorageUtils shareInstance] userDefaultSave:objects[@"avatar"] withKey:U_HImage];
            // 用户手机
            [[MSStorageUtils shareInstance] userDefaultSave:objects[@"phone"] withKey:U_Phone];

            AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
            [app requestIM_token];
        
            for (NSDictionary *dic in resonseObj[@"roleList"]) {
                NSString *roleName = dic[@"roleName"];
                NSString *roleId = dic[@"roleId"];
                NSString *roleCode = dic[@"roleCode"];
                [[MSStorageUtils shareInstance] userDefaultSave:roleName withKey:COMPANY_ROLE_NAME];
                [[MSStorageUtils shareInstance] userDefaultSave:roleId withKey:COMPANY_ROLE_ID];
                [[MSStorageUtils shareInstance] userDefaultSave:roleCode withKey:@"EduitString"];
            }
            if (infoNew.realName.length == 0){
                //没有完善个人信息---去完善个人信息
                PersonInfoViewController *infoVC = [[PersonInfoViewController alloc] init];
                infoVC.isFromeLogin = YES;
                [self.navigationController pushViewController:infoVC animated:YES];
            } else if ([NSString stringWithFormat:@"%@",infoNew.companyId].length < 1 || [infoNew.companyId isNil] == YES || [infoNew.companyId intValue] < 1){
                //没有绑定企业，去绑定企业
                SuoShuQiYeViewController  *VC = [[SuoShuQiYeViewController alloc] init];
                VC.isFromeLogin = YES;
                [self.navigationController pushViewController:VC animated:YES];
            } else if (infoNew.realName.length > 0 && [NSString stringWithFormat:@"%@",infoNew.companyId].length > 0){
                //完善完，绑定完企业---进主框架
                UIWindow *currentWindow = [BaseViewController getCurrentWindow];
                LiXingMainTabbarVC *tabBarController = [[LiXingMainTabbarVC alloc] init];
                tabBarController.delegate = self;
                tabBarController.selectedIndex = 0;
                [currentWindow setRootViewController:tabBarController];
                [currentWindow makeKeyAndVisible];
            }
            if (userIsLogin) {
                [JPUSHService setAlias:USER_ID completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
                    NSLog(@"%@",[[MSStorageUtils shareInstance] userDefaultGet:U_Id]);
                } seq:1];
            }
            
            
        }
        
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
        
    } withShowHud:NO];
    
    

}


///验证码登录
-(void)codeLogin{
    if (![self.phoneTF.text isValidPhone]) {
        showAlert(@"手机号码不正确");
        return;
    }
    if (![self.codeTF.text isValidCode]) {
        showAlert(@"验证码不正确");
        return;
    }
    if ([self.agreeString isEqualToString:@"0"]){
        showAlert(@"请先阅读平台服务协议和隐私协议");
        return;
    }
    

    NSString *url = [NSString stringWithFormat:@"%@%@?code=%@&mobile=%@&grant_type=app",DOMAIN_URL,LOGIN_URL,self.codeTF.text,self.phoneTF.text];
    
    [self loadLogin:url];
  

}
-(void)loadLogin:(NSString *)url{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    MBProgressHUD *hud = [MBProgressHUD showGif];
    [manager POST:url parameters:@{} headers:@{@"authorization":@"Basic dGVzdDp0ZXN0",@"userType":@"1",@"type":@"1"} progress:^(NSProgress * _Nonnull downloadProgrefilterWithServerCodess) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [hud hide];
        if (responseObject[@"code"]==0) {
            [[MSStorageUtils shareInstance] userDefaultSave:@"YES" withKey:USER_DEFAULT_KEY_MEMBER_IsLogin];
//            NSDictionary *objects = responseObject[@"data"];
//            [self saveUserInfo:objects];
            YLUserInfo * info = [YLUserMgr fetchUser];
            if (info == nil) info = [[YLUserInfo alloc] init];
            info.authorization = responseObject[@"access_token"];
            info.realName = responseObject[@"user_info"][@"realName"];
            info.companyId = [NSString stringWithFormat:@"%@", responseObject[@"user_info"][@"companyId"]];
            [[MSStorageUtils shareInstance] userDefaultSave:responseObject[@"access_token"] withKey:USER_DEFAULT_KEY_MEMBER_TOKEN];
            [YLUserMgr saveUser:info];
            [self getUserInfo];
        }
        else {
            showAlert(responseObject[@"msg"]);
        }
  
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [hud hide];
    }];

    
}
- (IBAction)ChangeButtonClick:(UIButton *)sender {
    if (self.changeButton.selected == YES) {
        [self.changeButton setImage:Image(@"small_select_icon") forState:UIControlStateNormal];
        self.changeButton.selected = NO;
        self.agreeString = @"1";
    } else {
        [self.changeButton setImage:Image(@"small_unSelect_icon") forState:UIControlStateNormal];
        self.changeButton.selected = YES;
        self.agreeString = @"0";
    }
}

-(void)textFieldDidChangeSelection:(UITextField *)textField{
    if (textField == self.phoneTF&&[self.typeString isEqualToString:@"0"]) {
        if (textField.text.length > 11) {
            textField.text = [textField.text substringToIndex:11];
        }
    }
    if (textField == self.codeTF && [self.typeString isEqualToString:@"0"]) {
        if (textField.text.length > 6) {
            textField.text = [textField.text substringToIndex:6];
        }
    }
    
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    
    
    
    NSString *shouldText = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    // 密码登录
    if ((textField == self.codeTF || textField == self.phoneTF) && [self.typeString isEqualToString:@"1"]) {
        
        if (shouldText.length>18) {
            shouldText = [shouldText substringToIndex:18];
            return NO;
        }
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ALPHANUM] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        return [string isEqualToString:filtered];
    }
    
    // 验证码
    else if (textField == self.codeTF  && [self.typeString isEqualToString:@"0"]) {
        if (textField.text.length > 6) {
            textField.text = [textField.text substringToIndex:6];
        }
    }
    
    // 手机号
    else if (textField == self.phoneTF  && [self.typeString isEqualToString:@"0"]) {
        if (textField.text.length > 11) {
            textField.text = [textField.text substringToIndex:11];
        }
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:kNUM] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        return [string isEqualToString:filtered];
    }
    
    
    return YES;
    
}
@end
